package com.java.simple.study.juc.pattern;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhoujunlin
 * @date 2022年11月07日 22:02
 * @desc
 */
@Slf4j(topic = "c.FileSaver")
public class FileSaver {
    private final String fileName;
    private final ObjectMapper objectMapper;
    private boolean changed;

    public FileSaver(String fileName) {
        this.fileName = fileName;
        objectMapper = new ObjectMapper();
    }

    public void change() {
        this.changed = true;
    }

    public void save(ConcurrentHashMap<String, String> info) {
        log.debug("need save {} ? {}", info, changed ? "yes" : "no");
        if (!changed) {
            return;
        }
        try {
            objectMapper.writeValue(new File(fileName), info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        changed = false;
    }

}
